import React, { useState, useRef, useEffect } from 'react'

// AI深度分析显示组件
const AIAnalysisDisplay = ({ analysisResult, sources = [] }) => {
  const [hoveredReference, setHoveredReference] = useState(null)
  const [hoveredSentence, setHoveredSentence] = useState(null)
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 })
  const hoverTimeoutRef = useRef(null)

  // 防抖处理引用悬停
  const handleReferenceHover = (referenceData, mouseEvent) => {
    // 清除之前的定时器
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    
    // 使用鼠标位置作为提示框位置，并确保不超出屏幕边界
    const tooltipWidth = 320  // 浮框宽度
    const tooltipHeight = 150 // 浮框高度
    const viewportWidth = window.innerWidth
    const viewportHeight = window.innerHeight
    
    let x = mouseEvent.clientX + 10 // 鼠标右侧10px
    let y = mouseEvent.clientY - 10 // 鼠标上方10px
    
    // 如果右侧空间不足，放在左侧
    if (x + tooltipWidth > viewportWidth - 20) {
      x = mouseEvent.clientX - tooltipWidth - 10
    }
    
    // 如果上方空间不足，放在下方
    if (y < 20) {
      y = mouseEvent.clientY + 20
    }
    
    // 如果下方空间不足，放在上方
    if (y + tooltipHeight > viewportHeight - 20) {
      y = mouseEvent.clientY - tooltipHeight - 10
    }
    
    // 确保不会超出屏幕边界
    x = Math.max(10, Math.min(x, viewportWidth - tooltipWidth - 10))
    y = Math.max(10, Math.min(y, viewportHeight - tooltipHeight - 10))
    
    const position = { x, y }
    setTooltipPosition(position)
    
    // 立即设置引用信息
    setHoveredReference(referenceData)
    
    // 延迟设置句子高亮，避免频繁切换
    hoverTimeoutRef.current = setTimeout(() => {
      setHoveredSentence(referenceData?.sentenceIndex)
    }, 150) // 150ms延迟
  }

  const handleReferenceLeave = () => {
    // 清除定时器
    if (hoverTimeoutRef.current) {
      clearTimeout(hoverTimeoutRef.current)
    }
    
    // 延迟清除，给用户时间移动到相邻引用
    hoverTimeoutRef.current = setTimeout(() => {
      setHoveredReference(null)
      setHoveredSentence(null)
    }, 100) // 100ms延迟
  }

  // 清理定时器
  useEffect(() => {
    return () => {
      if (hoverTimeoutRef.current) {
        clearTimeout(hoverTimeoutRef.current)
      }
    }
  }, [])

  // 处理简单格式（粗体和行内公式）- 返回HTML字符串
  const processSimpleFormatting = (text, key) => {
    if (!text || typeof text !== 'string') return text
    
    try {
      let processedText = text
      
      // 处理粗体 **text** 或 <BOLD>text</BOLD>
      const boldRegex1 = /\*\*(.+?)\*\*/g
      const boldRegex2 = /<BOLD>(.+?)<\/BOLD>/g
      
      // 先处理 <BOLD> 标签
      processedText = processedText.replace(boldRegex2, '<strong class="font-semibold text-gray-900">$1</strong>')
      
      // 再处理 ** 格式
      processedText = processedText.replace(boldRegex1, '<strong class="font-semibold text-gray-900">$1</strong>')
      
      // 处理行内数学公式 \( ... \)
      const mathInlineRegex = /\\\(([\s\S]*?)\\\)/g
      processedText = processedText.replace(mathInlineRegex, (match, formula) => {
        const formattedFormula = formatMathFormula(formula.trim(), false)
        return `<span class="inline-flex items-center bg-gray-100 px-2 py-1 rounded text-sm border font-mono">${formattedFormula}</span>`
      })
      
      // 处理块级数学公式 \[ ... \]
      const mathBlockRegex = /\\\[([\s\S]*?)\\\]/g
      processedText = processedText.replace(mathBlockRegex, (match, formula) => {
        const formattedFormula = formatMathFormula(formula.trim(), true)
        return `<div class="text-xl bg-white p-6 rounded-lg border-2 border-blue-200 shadow-sm my-4 text-center font-mono">${formattedFormula}</div>`
      })
      
      // 始终返回HTML字符串，不返回React元素
      return processedText
    } catch (error) {
      console.error('文本格式处理错误:', error)
      return text
    }
  }

  // 格式化数学公式
  const formatMathFormula = (formula, isBlock = false) => {
    if (!formula || typeof formula !== 'string') {
      return '公式解析错误'
    }
    
    try {
      let processedFormula = formula
      
      // 处理常见的数学符号和公式
      processedFormula = processedFormula
        // 处理分数 \frac{numerator}{denominator}
        .replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, (match, numerator, denominator) => {
          return `<div class="inline-block text-center mx-1">
            <div class="border-b border-gray-600 pb-1 px-2 text-sm">${numerator}</div>
            <div class="pt-1 px-2 text-sm">${denominator}</div>
          </div>`
        })
        // 处理上标 ^{...} 或 ^x
        .replace(/\^(\{[^}]+\}|\w+)/g, (match, sup) => {
          const content = sup.startsWith('{') ? sup.slice(1, -1) : sup
          return `<sup class="text-xs relative top-[-0.5em]">${content}</sup>`
        })
        // 处理下标 _{...} 或 _x
        .replace(/_(\{[^}]+\}|\w+)/g, (match, sub) => {
          const content = sub.startsWith('{') ? sub.slice(1, -1) : sub
          return `<sub class="text-xs relative bottom-[-0.5em]">${content}</sub>`
        })
        // 处理大括号
        .replace(/\\left\(/g, '<span class="text-2xl font-light">(</span>')
        .replace(/\\right\)/g, '<span class="text-2xl font-light">)</span>')
        .replace(/\\left\[/g, '<span class="text-2xl font-light">[</span>')
        .replace(/\\right\]/g, '<span class="text-2xl font-light">]</span>')
        .replace(/\\left\{/g, '<span class="text-2xl font-light">{</span>')
        .replace(/\\right\}/g, '<span class="text-2xl font-light">}</span>')
        // 处理数学符号
        .replace(/\\approx/g, '≈')
        .replace(/\\times/g, '×')
        .replace(/\\div/g, '÷')
        .replace(/\\pm/g, '±')
        .replace(/\\leq/g, '≤')
        .replace(/\\geq/g, '≥')
        .replace(/\\neq/g, '≠')
        .replace(/\\infty/g, '∞')
        .replace(/\\sum/g, '∑')
        .replace(/\\prod/g, '∏')
        .replace(/\\int/g, '∫')
        .replace(/\\alpha/g, 'α')
        .replace(/\\beta/g, 'β')
        .replace(/\\gamma/g, 'γ')
        .replace(/\\delta/g, 'δ')
        .replace(/\\epsilon/g, 'ε')
        .replace(/\\theta/g, 'θ')
        .replace(/\\lambda/g, 'λ')
        .replace(/\\mu/g, 'μ')
        .replace(/\\pi/g, 'π')
        .replace(/\\sigma/g, 'σ')
        .replace(/\\tau/g, 'τ')
        .replace(/\\phi/g, 'φ')
        .replace(/\\omega/g, 'ω')
        // 处理特殊变量（高亮显示）
        .replace(/\\text\{([^}]+)\}/g, '<span class="font-semibold text-blue-600">$1</span>')
        .replace(/\b(CAGR|PV|FV|n)\b/g, '<span class="font-semibold text-blue-600">$1</span>')
        // 处理百分号
        .replace(/\\%/g, '%')
        // 清理多余的转义
        .replace(/\\left/g, '')
        .replace(/\\right/g, '')
        .replace(/\\/g, '')
      
      return processedFormula
    } catch (error) {
      console.error('数学公式格式化错误:', error)
      return formula
    }
  }

  // 处理文本中的引用和格式
  const processTextWithReferences = (text, lineKey, sources) => {
    // 按句子分割
    const sentences = text.split(/(?<=[。！？])\s*/).filter(s => s.trim())
    
    return sentences.map((sentence, sentenceIndex) => {
      const sentenceKey = `${lineKey}-sentence-${sentenceIndex}`
      
      // 处理粗体
      let processedSentence = sentence.replace(/\*\*(.+?)\*\*/g, (match, content) => {
        return `<BOLD>${content}</BOLD>`
      })
      
      // 查找引用
      const referenceRegex = /\[\[(\d+)\]\]/g
      const parts = []
      let lastIndex = 0
      let match

      while ((match = referenceRegex.exec(processedSentence)) !== null) {
        // 添加引用前的文本
        if (match.index > lastIndex) {
          const textPart = processedSentence.slice(lastIndex, match.index)
          parts.push(textPart)
        }

        const refNumber = parseInt(match[1])
        const source = sources.find(s => s.position === refNumber)
        
        parts.push(`<span class="inline-flex items-center justify-center w-5 h-5 mx-1 bg-gray-400 text-white text-xs rounded-full cursor-pointer hover:bg-blue-500 transition-colors" data-ref="${refNumber}">${refNumber}</span>`)

        lastIndex = match.index + match[0].length
      }

      // 添加剩余文本
      if (lastIndex < processedSentence.length) {
        const textPart = processedSentence.slice(lastIndex)
        parts.push(textPart)
      }
      
      // 合并所有部分
      const combinedText = parts.join('')
      
      return (
        <span 
          key={sentenceKey}
          className={`inline transition-all duration-200 ${
            hoveredSentence === `${lineKey}-${sentenceIndex}`
              ? 'bg-blue-100 text-blue-900 rounded px-1' 
              : ''
          }`}
          dangerouslySetInnerHTML={{ __html: processSimpleFormatting(combinedText, sentenceKey) }}
          onMouseOver={(e) => {
            // 使用 onMouseOver 事件委托处理引用悬停
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              const refNumber = parseInt(target.dataset.ref)
              const source = sources.find(s => s.position === refNumber)
              if (source) {
                handleReferenceHover({ 
                  number: refNumber, 
                  source,
                  sentenceIndex: `${lineKey}-${sentenceIndex}`,
                  element: target
                }, e)
              }
            }
          }}
          onMouseMove={(e) => {
            // 实时更新浮框位置跟随鼠标
            if (hoveredReference) {
              const tooltipWidth = 320  // 浮框宽度
              const tooltipHeight = 150 // 浮框高度
              const viewportWidth = window.innerWidth
              const viewportHeight = window.innerHeight
              
              let x = e.clientX + 10 // 鼠标右侧10px
              let y = e.clientY - 10 // 鼠标上方10px
              
              // 如果右侧空间不足，放在左侧
              if (x + tooltipWidth > viewportWidth - 20) {
                x = e.clientX - tooltipWidth - 10
              }
              
              // 如果上方空间不足，放在下方
              if (y < 20) {
                y = e.clientY + 20
              }
              
              // 如果下方空间不足，放在上方
              if (y + tooltipHeight > viewportHeight - 20) {
                y = e.clientY - tooltipHeight - 10
              }
              
              // 确保不会超出屏幕边界
              x = Math.max(10, Math.min(x, viewportWidth - tooltipWidth - 10))
              y = Math.max(10, Math.min(y, viewportHeight - tooltipHeight - 10))
              
              const position = { x, y }
              setTooltipPosition(position)
            }
          }}
          onMouseOut={(e) => {
            // 使用 onMouseOut 事件委托处理引用离开
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              // 延迟清除，给用户时间移动到浮框
              setTimeout(() => {
                handleReferenceLeave()
              }, 100)
            }
          }}
          onClick={(e) => {
            // 使用 onClick 事件委托处理引用点击
            const target = e.target
            if (target && target.dataset && target.dataset.ref) {
              const refNumber = parseInt(target.dataset.ref)
              const source = sources.find(s => s.position === refNumber)
              if (source?.link) {
                window.open(source.link, '_blank')
              }
            }
          }}
        />
      )
    })
  }

  // 处理分析结果中的引用链接
  const processAnalysisResult = (text, sources = []) => {
    if (!text) return text

    // 1. 过滤掉 ">" 开头的行
    const lines = text.split('\n')
    const filteredLines = lines.filter(line => !line.trim().startsWith('>'))
    let cleanText = filteredLines.join('\n').trim()

    // 2. 过滤掉"最终数据:"部分（用于AI分析结果）
    const finalDataRegex = /最终数据:\s*\{[^}]*\}/g
    cleanText = cleanText.replace(finalDataRegex, '').trim()

    // 3. 按段落分割
    const paragraphs = cleanText.split(/\n\s*\n/).filter(p => p.trim())
    
    return (
      <div className="prose prose-sm max-w-none space-y-4">
        {paragraphs.map((paragraph, paragraphIndex) => {
          return processParagraph(paragraph, paragraphIndex, sources)
        })}
      </div>
    )
  }

  // 处理单个段落
  const processParagraph = (paragraph, paragraphIndex, sources) => {
    const lines = paragraph.split('\n').filter(line => line.trim())
    
    return (
      <div key={`paragraph-${paragraphIndex}`} className="mb-4">
        {lines.map((line, lineIndex) => {
          return processLine(line, `${paragraphIndex}-${lineIndex}`, sources)
        })}
      </div>
    )
  }

  // 处理单行内容
  const processLine = (line, lineKey, sources) => {
    const trimmedLine = line.trim()
    
    // 处理标题 - 按层级从多到少检查
    if (trimmedLine.startsWith('##### ')) {
      const title = trimmedLine.substring(6)
      return (
        <h5 key={lineKey} className="text-sm font-semibold mt-2 mb-1 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h5>
      )
    }
    
    if (trimmedLine.startsWith('#### ')) {
      const title = trimmedLine.substring(5)
      return (
        <h4 key={lineKey} className="text-base font-semibold mt-3 mb-2 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h4>
      )
    }
    
    if (trimmedLine.startsWith('### ')) {
      const title = trimmedLine.substring(4)
      return (
        <h3 key={lineKey} className="text-lg font-semibold mt-4 mb-2 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h3>
      )
    }
    
    if (trimmedLine.startsWith('## ')) {
      const title = trimmedLine.substring(3)
      return (
        <h2 key={lineKey} className="text-xl font-semibold mt-6 mb-3 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h2>
      )
    }

    if (trimmedLine.startsWith('# ')) {
      const title = trimmedLine.substring(2)
      return (
        <h1 key={lineKey} className="text-2xl font-bold mt-8 mb-4 text-gray-800">
          {processTextWithReferences(title, lineKey, sources)}
        </h1>
      )
    }
    
    // 处理列表项
    if (trimmedLine.startsWith('- ')) {
      const content = trimmedLine.substring(2)
      return (
        <div key={lineKey} className="ml-4 mb-1 flex">
          <span className="mr-2">•</span>
          <span>{processTextWithReferences(content, lineKey, sources)}</span>
        </div>
      )
    }
    
    // 处理普通段落
    if (trimmedLine) {
      return (
        <p key={lineKey} className="mb-2 leading-relaxed">
          {processTextWithReferences(trimmedLine, lineKey, sources)}
        </p>
      )
    }
    
    return null
  }

  if (!analysisResult) {
    return null
  }

  return (
    <>
      <div className="bg-gray-50 border border-gray-200 p-6 rounded-lg">
        <h4 className="font-semibold text-gray-800 mb-4 flex items-center">
          <span className="w-2 h-2 bg-purple-500 rounded-full mr-2"></span>
          AI分析详情
        </h4>
        <div className="text-gray-700 leading-relaxed">
          {processAnalysisResult(analysisResult, sources)}
        </div>
      </div>

      {/* 悬浮提示 */}
      {hoveredReference && hoveredReference.element && (
        <div 
          className="fixed z-50 bg-white border border-gray-200 rounded-lg shadow-xl max-w-md transition-all duration-200"
          style={{
            left: `${tooltipPosition.x}px`,
            top: `${tooltipPosition.y}px`,
            transform: 'translate(0, 0)' // 避免额外的变换
          }}
          onMouseEnter={() => {
            // 鼠标进入浮框时，清除离开定时器
            if (hoverTimeoutRef.current) {
              clearTimeout(hoverTimeoutRef.current)
            }
          }}
          onMouseLeave={() => {
            // 鼠标离开浮框时，立即清除悬停状态
            handleReferenceLeave()
          }}
        >
          {/* 小箭头指示器 */}
          <div className="absolute -top-2 left-4 w-4 h-4 bg-white border-l border-t border-gray-200 transform rotate-45"></div>
          
          {/* 内容区域 */}
          <div className="relative p-4">
            <div className="flex items-center mb-2">
              <span className="inline-flex items-center justify-center w-6 h-6 bg-blue-500 text-white text-xs rounded-full mr-2">
                {hoveredReference.number}
              </span>
              <div className="font-medium text-gray-900">数据来源</div>
            </div>
            {hoveredReference.source && (
              <>
                <div className="font-medium text-gray-800 mb-2 line-clamp-2">
                  {hoveredReference.source.title}
                </div>
                <div className="text-sm text-gray-600 mb-2">
                  {hoveredReference.source.snippet}
                </div>
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <span>{hoveredReference.source.date}</span>
                  <svg className="h-3 w-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                  </svg>
                </div>
              </>
            )}
          </div>
        </div>
      )}
    </>
  )
}

export default AIAnalysisDisplay
